package net.guerlab.smart.wx.service.controller.ma;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import net.guerlab.smart.wx.core.message.SendMsgResponse;
import net.guerlab.smart.wx.core.message.WxMaSubscribeMessageData;
import net.guerlab.smart.wx.core.message.WxMaSubscribeMessageSendRequest;
import net.guerlab.smart.wx.service.controller.AbstractMsgController;
import net.guerlab.smart.wx.service.service.WxMaManagerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 微信-小程序-订阅消息
 *
 * @author guer
 */
public abstract class AbstractWxMaSubscribeMsgController
        extends AbstractMsgController<WxMaSubscribeMessageSendRequest> {

    protected WxMaManagerService maManagerService;

    @Autowired
    public void setMaManagerService(WxMaManagerService maManagerService) {
        this.maManagerService = maManagerService;
    }

    @Override
    protected Map<String, SendMsgResponse> sendMsg0(String appId, Collection<String> openIds,
            WxMaSubscribeMessageSendRequest request) {
        WxMaSubscribeMessageData msg = request.getMsg();

        WxMaMsgService wxMaMsgService = maManagerService.getService(appId).getMsgService();

        Map<String, SendMsgResponse> result = new ConcurrentHashMap<>(openIds.size());

        List<WxMaSubscribeMessage.Data> dataList = msg.getData().stream().map(this::toMsgData).filter(Objects::nonNull)
                .collect(Collectors.toList());

        openIds.forEach(openId -> {
            WxMaSubscribeMessage sendMsg = new WxMaSubscribeMessage();
            sendMsg.setData(dataList);
            sendMsg.setPage(msg.getPage());
            sendMsg.setTemplateId(msg.getTemplateId());
            sendMsg.setToUser(openId);

            SendMsgResponse response = new SendMsgResponse();
            result.put(openId, response);
            try {
                wxMaMsgService.sendSubscribeMsg(sendMsg);
                response.setStatus(true);
            } catch (WxErrorException e) {
                WxError error = e.getError();
                response.setErrorCode(error.getErrorCode());
                response.setErrorMsg(error.getErrorMsg());
            } catch (Exception e) {
                response.setErrorMsg(e.getLocalizedMessage());
            }
        });

        return result;
    }

    private WxMaSubscribeMessage.Data toMsgData(WxMaSubscribeMessageData.TemplateData templateData) {
        if (templateData == null) {
            return null;
        }
        String name = StringUtils.trimToNull(templateData.getName());
        if (name == null) {
            return null;
        }

        WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
        data.setName(name);
        data.setValue(templateData.getValue());
        return data;
    }
}
